﻿using Manon.Admin.ApplicationCore.Common;
using Manon.Admin.ApplicationCore.Infrastructure;
using Manon.Admin.Web.ApplicationCore.Dtos;
using Manon.Admin.Web.ApplicationCore.Dtos.Member;
using Manon.Admin.Web.ApplicationCore.Entities.Member;
using Manon.Admin.Web.ApplicationCore.Interfaces;
using Manon.Autofac;
using Manon.Core.Commons;
using Manon.Repository;
using Manon.Repository.Collections;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Manon.Admin.Web.ApplicationCore.Services
{
    public class MemberService : IMemberService, ISingletonDependency
    {
        #region 会员等级
        /// <summary>
        /// 获取会员等级
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<GetMemberLevelOutput> GetMemberLevel(int Id)
        {
            if (Id <= 0) return new GetMemberLevelOutput() { Enabled = true };

            var logger = Resolver.Resolve<ILogger<MemberService>>();
            try
            {


                var unitOfWork = Resolver.Resolve<IUnitOfWork<AdminDbContext>>();

                var result = await unitOfWork.GetRepository<MemberLevel>().FindAsync(Id);

                return result.ConvertTo<MemberLevel, GetMemberLevelOutput>(); 
            }
            catch (Exception ex)
            {
                logger.LogError("获取资讯异常", ex);
                throw;
            }
        }

        /// <summary>
        /// 获取会员等级列表
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<IPagedList<GetMemberLevelOutput>> GetMemberLevelPagedList(GetMemberLevelPagedListInput Input)
        {
            var logger = Resolver.Resolve<ILogger<MemberService>>();
            try
            {
                var unitOfWork = Resolver.Resolve<IUnitOfWork<AdminDbContext>>();

                Expression<Func<MemberLevel, bool>> predicate = null;
                var result = await unitOfWork.GetRepository<MemberLevel>().GetPagedListAsync<GetMemberLevelOutput>(predicate, Input);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError("获取资讯列表异常", ex);
                throw;
            }
        }

        /// <summary>
        /// 保存会员等级 
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Result> SaveMemberLevel(SaveMemberLevelInput Input)
        {
            var logger = Resolver.Resolve<ILogger<RoleService>>();
            try
            {
                var identityUser = Resolver.Resolve<IIdentityUser>();
                var unitOfWork = Resolver.Resolve<IUnitOfWork<AdminDbContext>>();
                var repos = unitOfWork.GetRepository<MemberLevel>();
                var result = await repos.FindAsync(Input.Id);
                if (result == null)
                {
                    result = new MemberLevel();
                    result.LevelName = Input.LevelName;
                    result.OrderIndex = Input.OrderIndex;
                    result.Enabled = Input.Enabled;
                    result.CreateTime = DateTime.Now;
                    result.UpdateTime = DateTime.Now;
                    result.OrderIndex = Input.OrderIndex;
                    result.CreateBy = identityUser.UserId;
                    result.UpdateBy = identityUser.UserId;
                    await repos.InsertAsync(result);
                }
                else
                {
                    result.LevelName = Input.LevelName;
                    result.OrderIndex = Input.OrderIndex;
                    result.Enabled = Input.Enabled;
                    result.UpdateTime = DateTime.Now;
                    result.OrderIndex = Input.OrderIndex;
                    result.UpdateBy = identityUser.UserId;
                    repos.Update(result);
                }
                await unitOfWork.SaveChangesAsync();
                return Result.Successed("保存成功!");
            }
            catch (Exception ex)
            {
                logger.LogError("保存会员等级异常", ex);
                throw;
            }
        }


        /// <summary>
        /// 设置会员等级是否可用
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Result> SetMemberLevelEnabled(int Id, bool Enabled)
        {
            var logger = Resolver.Resolve<ILogger<RoleService>>();
            try
            {

                var unitOfWork = Resolver.Resolve<IUnitOfWork<AdminDbContext>>();

                var news = await unitOfWork.GetRepository<MemberLevel>().FindAsync(Id);
                if (news == null) return null;
                news.Enabled = Enabled;
                await unitOfWork.SaveChangesAsync();
                return Result.Successed("设置成功!");

            }
            catch (Exception ex)
            {
                logger.LogError("设置会员等级是否可用异常", ex);
                throw;
            }
        }
        #endregion



        #region 会员管理

        /// <summary>
        /// 获取会员等级列表
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<List<GetMemberLevelOutput>> GetMemberLevelList()
        {
            var logger = Resolver.Resolve<ILogger<MemberService>>();
            try
            {
                var unitOfWork = Resolver.Resolve<IUnitOfWork<AdminDbContext>>();
                var result = await unitOfWork.GetRepository<MemberLevel>().GetAll().OrderBy(n => n.OrderIndex).ToListAsync();
                if (result == null || result.Count == 0) return new List<GetMemberLevelOutput>();

                return result.ConvertTo<MemberLevel, GetMemberLevelOutput>();
                 
            }
            catch (Exception ex)
            {
                logger.LogError("获取会员等级列表异常", ex);
                throw;
            }
        }

        /// <summary>
        /// 获取会员管理
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<GetMemberOutput> GetMember(int Id)
        {
            if (Id <= 0) return new GetMemberOutput() { Enabled = true, Sex = 1 };

            var logger = Resolver.Resolve<ILogger<MemberService>>();
            try
            {


                var unitOfWork = Resolver.Resolve<IUnitOfWork<AdminDbContext>>();

                var result = await unitOfWork.GetRepository<Member>().FindAsync(Id);

                return result.ConvertTo<Member, GetMemberOutput>(); 
            }
            catch (Exception ex)
            {
                logger.LogError("获取会员管理异常", ex);
                throw;
            }
        }

        /// <summary>
        /// 获取会员管理列表
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<IPagedList<GetMemberOutput>> GetMemberPagedList(GetMemberPagedListInput Input)
        {
            var logger = Resolver.Resolve<ILogger<MemberService>>();
            try
            {
                var unitOfWork = Resolver.Resolve<IUnitOfWork<AdminDbContext>>();
                var levels = await unitOfWork.GetRepository<MemberLevel>().GetAll().ToListAsync();


                Expression<Func<Member, bool>> predicate = null;
                if (Input.Enabled.HasValue)
                {
                    predicate = n => n.Enabled == Input.Enabled.Value;
                }
                if (!string.IsNullOrEmpty(Input.Keyword))
                {
                    predicate = n => n.MemberName.Contains(Input.Keyword) || n.MemberCnName.Contains(Input.Keyword);
                }
                if (Input.Sex > 0)
                {
                    predicate = n => n.Sex == Input.Sex;
                }
                if (Input.Level > 0)
                {
                    predicate = n => n.Level == Input.Level;
                }
                if (!string.IsNullOrEmpty(Input.RegisteStartTime))
                {
                    predicate = n => n.RegisteTime >= DateTime.Parse(Input.RegisteStartTime);
                }
                if (!string.IsNullOrEmpty(Input.RegisteEndTime))
                {
                    predicate = n => n.RegisteTime <= DateTime.Parse(Input.RegisteEndTime);
                }
                var result = await unitOfWork.GetRepository<Member>().GetPagedListAsync<GetMemberOutput>(predicate, Input);

                if (result != null && result.Items != null)
                {
                    foreach (var item in result.Items)
                    {
                        item.LevelName = levels?.Where(n => n.Id == item.Id).FirstOrDefault()?.LevelName;
                    }
                }

                return result;
            }
            catch (Exception ex)
            {
                logger.LogError("获取会员管理列表异常", ex);
                throw;
            }
        }

        /// <summary>
        /// 保存会员管理
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Result> SaveMember(SaveMemberInput Input)
        {
            var logger = Resolver.Resolve<ILogger<RoleService>>();
            try
            {
                var identityUser = Resolver.Resolve<IIdentityUser>();
                var unitOfWork = Resolver.Resolve<IUnitOfWork<AdminDbContext>>();
                var repos = unitOfWork.GetRepository<Member>();
                var result = await repos.FindAsync(Input.Id);
                if (result == null)
                {
                    result = new Member();
                    result.Address = Input.Address ?? "";
                    result.Email = Input.Email ?? "";
                    result.HeadPortrait = Input.HeadPortrait ?? "";
                    result.Level = Input.Level;
                    result.MemberCnName = Input.MemberCnName ?? "";
                    result.MemberName = Input.MemberName ?? "";
                    result.Mobile = Input.Mobile ?? "";
                    result.Password = "";
                    result.RegisteTime = DateTime.Now;
                    result.Sex = Input.Sex;
                    result.Enabled = Input.Enabled;
                    result.CreateTime = DateTime.Now;
                    result.UpdateTime = DateTime.Now;
                    result.CreateBy = identityUser.UserId;
                    result.UpdateBy = identityUser.UserId;
                    await repos.InsertAsync(result);
                }
                else
                {
                    result.Address = Input.Address ?? "";
                    result.Email = Input.Email ?? "";
                    result.HeadPortrait = Input.HeadPortrait ?? "";
                    result.Level = Input.Level;
                    result.MemberCnName = Input.MemberCnName ?? "";
                    result.MemberName = Input.MemberName ?? "";
                    result.Mobile = Input.Mobile ?? "";
                    result.Password = "";
                    result.RegisteTime = DateTime.Now;
                    result.Sex = Input.Sex;
                    result.Enabled = Input.Enabled;
                    result.UpdateTime = DateTime.Now;
                    result.UpdateBy = identityUser.UserId;
                    repos.Update(result);
                }
                await unitOfWork.SaveChangesAsync();
                return Result.Successed("保存成功!");
            }
            catch (Exception ex)
            {
                logger.LogError("保存会员管理异常", ex);
                throw;
            }
        }


        /// <summary>
        /// 设置会员管理是否可用
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Result> SetMemberEnabled(int Id, bool Enabled)
        {
            var logger = Resolver.Resolve<ILogger<RoleService>>();
            try
            {

                var unitOfWork = Resolver.Resolve<IUnitOfWork<AdminDbContext>>();

                var news = await unitOfWork.GetRepository<Member>().FindAsync(Id);
                if (news == null) return null;
                news.Enabled = Enabled;
                await unitOfWork.SaveChangesAsync();
                return Result.Successed("设置成功!");

            }
            catch (Exception ex)
            {
                logger.LogError("设置会员管理是否可用异常", ex);
                throw;
            }
        }
        #endregion
    }
}
